package com.atty.dms.common.biz.user;

import com.atty.dms.common.convention.exception.ClientException;
import com.atty.dms.tools.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@AllArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {


    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求路径和方法
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        // 定义需要放行的路径
        if ("/api/dms/admin/user/login".equals(requestURI)) {
            return true; // 放行登录接口
        }
        if ("/api/dms/admin/user".equals(requestURI) && "POST".equalsIgnoreCase(method)) {
            return true; // 放行 POST /api/dms/admin/user
        }

        // 从请求头中获取Token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new ClientException("缺少有效的身份凭证");
        }

        // 去掉 "Bearer " 前缀
        while (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        // 验证Token是否有效
        if (!jwtUtil.validateToken(token)) {
            throw new ClientException("身份凭证无效或已过期");
        }

        // 解析Token，获取Claims
        Claims claims = jwtUtil.parseToken(token);

        // 提取用户信息
        String username = claims.getSubject(); // 用户名
        Long userId = claims.get("userId", Long.class); // 用户ID
        String userIdStr = String.valueOf(userId);

        // 创建UserInfoDTO对象
        UserInfoDTO userInfoDTO = UserInfoDTO.builder()
                .userId(userIdStr)
                .username(username)
                .build();

        // 将用户信息存入上下文
        UserContext.setUser(userInfoDTO);

        return true;
    }
}